home *** CD-ROM | disk | FTP | other *** search
- Path: news.iastate.edu!pholland
- From: pholland@iastate.edu (Paul J Hollander)
- Newsgroups: comp.sys.amiga.programmer
- Subject: Re: Random Number Generation
- Date: 24 Feb 1996 18:51:02 GMT
- Organization: Iowa State University, Ames, Iowa USA
- Message-ID: <4gnmmm$ru9@news.iastate.edu>
- References: <199602071623.QAA00075@sable.ox.ac.uk> <1100.6613T1273T666@himolde.no> <692.6619T1254T1752@in.net> <4g2bi9$1fls@rs18.hrz.th-darmstadt.de>
- NNTP-Posting-Host: du139-206.cc.iastate.edu
-
- >In article <692.6619T1254T1752@in.net>, mave@in.net (John J. Maver, Jr.) writes:
- >>
- >> I want to generate a randum number, like BASIC allowed you to do, in
- >> C. I want a function that I can call with the High and Low numbers and then
- >> have it return a number between them.
- >>
- >>
- >> What I have so far is:
- >>
- >> <sb>
- >>
- >> float rndnum(float low, float high)
- >> {
- >> float num; /*used to temporarily hold a rnd num*/
- >>
- >>
- >> srand=(time(NULL)); /*generate a new seed*/
- >> num=rand()%1000; /*Try to modify rand()s output to be*/
- >> num/=100; /*between 0 and 1*/
- >> num=(num*high)+low; /*Make num fit the specified range*/
- >>
- >> return num;
- >> }
- >>
- >> It doesn't quite work. Any hints?
- >>
- >> <sb>
-
- I needed a random number generator a few weeks ago and hacked this out
- figuring out how to do it. System: A3000/25, 6 MB, OS 3.1, SAS/C 5.10.
- Hope it helps.
-
- I wonder if the problem is in the line num=(num*high)+low. If so, try
- changing it to num = (num * (high - low + 1)) + low.
-
- Paul Hollander pholland@iastate.edu
- Behold the tortoise: he makes no progress unless he sticks his neck out.
-
- -------------------
-
- /* Title = Random_Num_Gen */
- /* Random number generator using the time clock
- Generates integer random numbers from 10 to 20,
- including both 10 and 20
-
- Drand48() and srand48() require math.h
- Time() and ctime() require time.h
- */
-
- #include <stdio.h>
- #include <math.h>
- #include <time.h>
-
- void main()
- {
- float rnd;
- int L1, bottom, top, interval, x;
- long t;
-
- bottom = 10;
- top = 20;
- interval = top - bottom + 1;
- L1 = x = 0;
-
- /* Put the number of seconds in the time clock into variable t */
-
- time (&t);
- printf ("Seconds = %d\n", t);
- printf ("Current time is %s\n", ctime(&t));
-
- /* Seed the randomize function with t */
-
- srand48(t);
-
- /* The drand48() function gets a random number >= 0.0 and < 1.0 */
-
- for (L1 = 1; L1 <= 10; L1++)
- {
- rnd = drand48();
- if (L1 == 9)
- rnd = .0;
- if (L1 == 10)
- rnd = .999999;
- x = rnd * interval + bottom;
- printf ("Random number = %6f\n", rnd);
- printf (" %d <= %d <= %d\n", bottom, x, top);
- }
-
- printf ("\n\n");
- }
-
-